package com.example.demo20230927;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class ApiService {

    @Value("${app.id}")
    private String appId;

    @Value("${app.key}")
    private String appKey;

    private static final String URI = "/vivogpt/completions";
    private static final String DOMAIN = "api-ai.vivo.com.cn";
    private static final String METHOD = "POST";

    public String syncVivoGpt(String prompt) {
        Map<String, String> params = new HashMap<>();
        params.put("requestId", UUID.randomUUID().toString());

        Map<String, Object> data = new HashMap<>();
        data.put("prompt", prompt); // 使用传入的提示词
        data.put("model", "vivo-BlueLM-TB");
        data.put("sessionId", UUID.randomUUID().toString());
        Map<String, Object> extra = new HashMap<>();
        extra.put("temperature", 0.9);
        data.put("extra", extra);

        HttpHeaders headers = new HttpHeaders();

        Map<String, String> authHeaders = AuthUtil.genSignHeaders(appId, appKey, METHOD, URI, params);
        authHeaders.forEach(headers::set);

        headers.add("Content-Type", "application/json");

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(data, headers);

        String url = String.format("https://%s%s", DOMAIN, URI);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, params);

        // 返回响应内容
        return response.getBody();
    }
}
